package cn.cyh.user.controller;

import cn.cyh.Dto.UserDto;
import cn.cyh.basic.exception.BusinessException;
import cn.cyh.basic.uitls.AJaxResult;
import cn.cyh.basic.uitls.PageList;
import cn.cyh.org.query.EmployeeQuery;
import cn.cyh.user.domain.User;
import cn.cyh.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    // 新增和修改 put
    @PutMapping
    public AJaxResult addOrUpdate(@RequestBody User user){
        try {
            System.out.println();
            if (user.getId()==null){ // 如果没有则为添加
                userService.save(user);
            } else{ // 否则是修改
                userService.update(user);
            }
            return AJaxResult.myself();

        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }
    // 删除 delete
    @DeleteMapping("/{id}")
    public AJaxResult remove(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AJaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }

    // 查询 get
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.loadById(id);
    }

    // 查询所有部门
    @GetMapping
    public List<User> queryAll(){
        return userService.loadAll();
    }

    // 分页查询
    @PostMapping
    public PageList<User> queryPage(@RequestBody EmployeeQuery query){
        PageList<User> employeePageList = userService.queryPage(query);
        return employeePageList;
    }
    // 批量删除
    @PatchMapping
    public AJaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            userService.patchDelete(ids);
            return AJaxResult.myself();
        } catch (Exception e){
            System.out.println();
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }

    @PostMapping("/phone/register")
    public AJaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AJaxResult.myself();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("系统繁忙");
        }
    }
}
